package com.gxc.interceptor;

import com.gxc.entity.User;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * 登录拦截器.
 *
 * @author 宫新程
 * @since 2019/2/14 9:33
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

  private ThreadLocal<Long> needTime = new ThreadLocal<>();

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
      throws Exception {
    needTime.set(System.currentTimeMillis());
    log.info("访问Url：{}", request.getRequestURL());
    HttpSession session = request.getSession();
    // 判断Session中是否登录
    User user = (User) session.getAttribute("login_user");
    if (user != null) {
      log.info("LoginInterceptor：用户已经登录, 用户ID：{}", user.getId());
      return true;
    }
    log.warn("LoginInterceptor：用户未登录，跳转到登录页面...");
    response.sendRedirect(request.getServletContext().getContextPath() + "/toLogin");
    return false;
  }

  @Override
  public void postHandle(
      HttpServletRequest request,
      HttpServletResponse response,
      Object handler,
      ModelAndView modelAndView)
      throws Exception {
    Long start = needTime.get();
    log.info("消耗时间：{}", (System.currentTimeMillis() - start));
  }

  @Override
  public void afterCompletion(
      HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
      throws Exception {}
}
